package com.ygy.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.org.apache.xpath.internal.operations.Or;
import com.ygy.entity.Orders;
import com.ygy.entity.Products;
import com.ygy.entity.VO.UserOrderVO;
import com.ygy.mapper.OrdersMapper;
import com.ygy.service.impl.OrdersServiceImpl;
import com.ygy.service.impl.ProductsServiceImpl;
import com.ygy.utils.OrderNumberGenerator;
import com.ygy.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author Ye
 * @since 2024-03-14
 */
@RestController
@RequestMapping("/ord")
public class OrdersController {

    @Autowired
    private  OrdersServiceImpl ordersService;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderNumberGenerator orderNumberGenerator;

    @Autowired
    private ProductsServiceImpl productsService;





    /**
     * 新增订单
     *
     * @param order 订单对象
     * @return 响应状态
     */
    @PostMapping("/add")
    public Result addOrder(@RequestBody Orders order) {
        // 调用服务层方法保存订单
        System.out.println(order+"输出订单");


        Integer productId = order.getProductId();
         Products product  = productsService.getById(productId);
         order.setPicture(product.getPicture());
         order.setSellId(product.getCreateuser());
         order.setProductName(product.getProductName());
         order.setTotalPrice(product.getPrice());
        //创建订单号

        String orderNumber = orderNumberGenerator.generateOrderNumber();
        order.setOrderNumber(orderNumber);
        boolean result = ordersService.save(order);
        if (result) {
            // 保存成功，返回成功响应
            return Result.success(order,"下单成功");
        } else {
            // 保存失败，返回失败响应
            return Result.error("购买出错");
        }
    }

    // 获取指定用户的所有买到订单
    @GetMapping("/{userId}/orders")
    public Result<IPage<UserOrderVO>> getUserOrders(@PathVariable Integer userId,
                                                    @RequestParam(defaultValue = "1") Integer pageNum,
                                                    @RequestParam(defaultValue = "5") Integer pageSize) {
        System.out.println("打印输出");
        IPage<UserOrderVO> userOrdersPage = ordersService.getUserOrders(userId, pageNum, pageSize);

        System.out.println("打印输出" + userOrdersPage);
        return Result.success(userOrdersPage);
    }

    // 获取指定用户的所有卖出订单
    @GetMapping("/{userId}/sellOrders")
    public Result<IPage<UserOrderVO>> getsellOrder(@PathVariable Integer userId,
                                                    @RequestParam(defaultValue = "1") Integer pageNum,
                                                    @RequestParam(defaultValue = "5") Integer pageSize) {
        System.out.println("打印输出");
        IPage<UserOrderVO> userOrdersPage = ordersService.getsellOrder(userId, pageNum, pageSize);

        System.out.println("打印输出" + userOrdersPage);
        return Result.success(userOrdersPage);
    }


    //分页查询和模糊查询
    @GetMapping("/page")
    public IPage<Orders> findPage(@RequestParam Integer pageNum,
                                    @RequestParam Integer pageSize,
                                    @RequestParam(defaultValue = "") String productName) {

        IPage<Orders> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("product_name", productName);
        return ordersService.page(page,queryWrapper);

    }


    //批量删除
    ////批量删除
    @PostMapping("/delete")
    public Result deleteOrder( @RequestBody List<String> orderNumber) {
        System.out.println("进入删除");
        System.out.println(orderNumber+"++++++++++++++++++++============+++++++");
        for (String order : orderNumber) {
            boolean delete = ordersService.removeById(order);
            if (!delete) {
                return Result.error("删除失败");
            }
        }
        return Result.success();
    }

    //修改订单状态的接口
    @PutMapping("/update-status/{orderId}")
    public Result updateOrderStatus(@PathVariable("orderId") Integer orderId,
                                    @RequestParam("status") String newStatus){
            // 检查订单ID和状态是否为空
            if (orderId == null || newStatus == null) {
                return Result.error("订单ID或状态不能为空") ;
            }
        // 创建更新条件
        UpdateWrapper<Orders> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_id", orderId); // 设置更新条件为订单ID匹配
        // 设置更新内容
        updateWrapper.set("status", newStatus); // 更新订单状态
        // 执行更新操作
        int result = ordersMapper.update(null, updateWrapper); // 第一个参数为null，因为updateWrapper中已经包含了更新的条件和内容
        // 根据更新结果返回响应
        if (result > 0) {
            return Result.success("订单状态更新成功") ;
        } else {
            return Result.error("订单状态更新失败，可能未找到对应的订单");
        }
    }
    //家评价
    @PutMapping("/evaluated/{orderId}")
    public Result updateOrderEvaluated(@PathVariable("orderId") Integer orderId,
                                    @RequestParam("evaluated") String evaluated){
        // 检查订单ID和状态是否为空
        if (orderId == null || evaluated == null) {
            return Result.error("订单ID或状态不能为空") ;
        }
        // 创建更新条件
        UpdateWrapper<Orders> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_id", orderId); // 设置更新条件为订单ID匹配
        // 设置更新内容
        if ("买家已评论".equals(evaluated)){
            updateWrapper.set("buyer_evaluated", evaluated);
        } else if ("卖家已评论".equals(evaluated)) {
            updateWrapper.set("seller_evaluated", evaluated);
        }
        // 执行更新操作
        int result = ordersMapper.update(null, updateWrapper); // 第一个参数为null，因为updateWrapper中已经包含了更新的条件和内容
        // 根据更新结果返回响应
        if (result > 0) {
            return Result.success("评论完成") ;
        } else {
            return Result.error("订单状态更新失败，可能未找到对应的订单");
        }
    }

    //获取单个订单
    @GetMapping("{orderId}")
    public Result getOrder(@PathVariable("orderId") Integer orderId){

         Orders order = ordersService.getById(orderId);

         return Result.success(order);

    }

    //订单搜索
//    public IPage<UserOrderVO> getPage(@RequestParam Integer pageNum,
//                                       @RequestParam Integer pageSize,
//                                       @RequestParam(defaultValue = "") String productName){
//
//
//    }
}
